//index.js
//获取应用实例
var app = getApp()
//录音管理需要的参数
const util = require('../../utils/util.js')
const auth = require('../../utils/auth.js')
const recorderManager = wx.getRecorderManager()
const innerAudioContext = wx.createInnerAudioContext()
var tempFilePath;

Page({
    data: {
        j: 1,//帧动画初始图片
        isSpeaking: false,//是否正在说话
        voices: [],//音频数组
        transBtn:false,
        transFont:'中文',
        transBack:'英文',
        transData:'zh',
        inputFont:'中-英',
        scrollTop:'',
        isEmpty:true,
        fixed:'translate-input',
        container:'translate-container',
        value:'',
        sourse:'',
        textTranArr:[] ,  //输入文本和翻译之后的数组
        listText:{
            inputText:'',
            tranText:'',
            chinese:'中',
            English:'英'
        }
    },
    onLoad: function () {
       //   var that = this;
       //  wx.getLocation({
       //      type: 'wgs84',
       //     success: function(res) {
       //      if(res){
       //          var latitude = res.latitude
       //          var longitude = res.longitude
               
       //            that.setData({
       //                latitude:latitude,
       //                longitude:longitude
       //          }) 
               
       //      }
          
       //   }
       // })
  
    },

    change: function () {
      var that = this;
      if (that.data.transData == 'zh') {
        that.setData({
          transFont:'英文',
          transBack:'中文',
          transData:'en',
          inputFont:'英-中'
        })
      }else if (that.data.transData == "en") {
        that.setData({
          transFont:'中文',
          transBack:'英文',
          transData:'zh',
          inputFont:'中-英'
        })
      }
    },

    clear:function(){
      this.setData({
        value:''
      })
    },

    scroll:function (e){
      var that = this;
      var top = e.detail.scrollTop;
      if (top > 45) {
        that.setData({
          fixed:'translate-input2',
          container:'translate-container2',
          transBtn:true
        });

      }else{
        that.setData({
          fixed:'translate-input',
          container:'translate-container',
          transBtn:false
        })
      }
    },

    goTran:function(e){  //点击输入完成之后开始翻译
      var temp = e.detail.value;
      var that = this;
      if (temp == '') {
        that.setData({
          isEmpty:true
        })
      }else{
        that.setData({
          isEmpty:false
        })
      }
      that.setData({
        sourse:temp
      })
    }, 
    touch:function(e){
       var that = this;
       var value = that.data.sourse;
       if (value == '' || value == undefined) {
          wx.showToast({
            title:'请输入翻译内容',
            icon: 'none'
          })
          return;
       }
       wx.showToast({
        title:'翻译中',
        icon:'loading',
        duration: 1000
       })
       var _self = this ;
       var temp = 'listText.inputText';
       _self.setData({
        [temp] :value
      })
      util.ajax({
            url:'act/actapi/tmt_api',
            data:{
                source_text:that.data.sourse,
                type:'text',
                lang:that.data.transData
            },
            header: {
              'content-type': 'application/json' // 默认值
          },
          success: function(res) {
              if (res.errorcode == 100001) {
                wx.showToast({
                  title:res.msg,
                  icon: 'none'
                })
                return;
              }
              var trantxt = res.data.targetText;
              var target = res.data.target;
              var chineseTemp='listText.chinese';
              var englishTemp='listText.English';
              if (target == "en") {
                that.setData({
                  [chineseTemp]:'中',
                  [englishTemp]:'英'
                })
              }else{
                that.setData({
                  [chineseTemp]:'英',
                  [englishTemp]:'中'
                })
              }
              var tranTxt='listText.tranText';
              that.setData({
                  [tranTxt]:trantxt
               });
              var textTranArrTemp = that.data.textTranArr;
              textTranArrTemp.unshift(that.data.listText);
              that.setData({
                textTranArr:textTranArrTemp,
                value:'',
                sourse:'',
                scrollTop:0
              })
            }
        })

    },
    //手指按下
    touchdown: function () {
        console.log("手指按下了...")
        console.log("new date : " + new Date)
        var _this = this;
        speaking.call(this);
        this.setData({
            isSpeaking: true
        })
        //开始录音      
        const options = {

            duration: 2000,

            sampleRate: 44100,

            numberOfChannels: 1,

            encodeBitRate: 192000,

            format: 'mp3',

            frameSize: 50
         };
       recorderManager.start(options);
//        recorderManager.onStart(() => {
//         console.log('recorder start')
// })
    },
    //手指抬起
    touchup: function () {
        console.log("手指抬起了...")
        var _this = this;
        this.setData({
            isSpeaking: false,
        })
        clearInterval(this.timer)
        recorderManager.onStop((res) => {
        if(recorderManager.onFrameRecorded){
                    console.log('11111')   
                    //debugger;
                recorderManager.onFrameRecorded((res) => {
                    //debugger;
                      console.log('22222');
                      console.log(res);
                      const { frameBuffer } = res                     
                      console.log('frameBuffer.byteLength', frameBuffer.byteLength)
                  })
                }else{
                    //请升级你的微信版本
                }
                 //持久保存             
                wx.saveFile({
                  tempFilePath: res.tempFilePath,
                  success: function (res) {
                    //本地文件存储的大小限制为 100M
                        var savedFilePath = res.savedFilePath
                        console.log("savedFilePath: " + savedFilePath)
                    }
                })
                wx.showToast({
                  title: '恭喜!录音成功',
                  icon: 'success',
                  duration: 1000
                })
                //获取录音音频列表
                wx.getSavedFileList({
                    success: function (res) {
                        var voices = [];
                        for (var i = 0; i < res.fileList.length; i++) {
                            //格式化时间
                            var createTime = new Date(res.fileList[i].createTime)
                            //将音频大小B转为KB
                            var size = (res.fileList[i].size / 1024).toFixed(2);
                            var voice = { filePath: res.fileList[i].filePath, createTime: createTime, size: size };
                            console.log("文件路径: " + res.fileList[i].filePath)
                            console.log("文件时间: " + createTime)
                            console.log("文件大小: " + size)
                            voices = voices.concat(voice);
                        }
                        _this.setData({
                            voices: voices
                        })
                    }
                });      
           console.log('recorder stop', res)
      });
    },
    //点击播放录音
    gotoPlay: function (e) {
        var filePath = e.currentTarget.dataset.key;
        //点击开始播放
        wx.showToast({
            title: '开始播放',
            icon: 'success',
            duration: 1000
        })
        wx.playVoice({
            filePath: filePath,
            success: function () {
                wx.showToast({
                    title: '播放结束',
                    icon: 'success',
                    duration: 1000
                })
            }
        })
    }
})
//麦克风帧动画
function speaking() {
    var _this = this;
    //话筒帧动画
    var i = 1;
    this.timer = setInterval(function () {
        i++;
        i = i % 5;
        _this.setData({
            j: i
        })
    }, 200);
}